import { observable, action } from 'mobx';
import { message } from 'antd';
import { WeaTableNew, WeaForm } from 'comsMobx';
import { WeaLocaleProvider } from 'ecCom';
import * as API_SEARCH_REQ from '../apis/accountListApi';
import SearchStore from './common/SearchStore';
import { getTodo, getDoing } from '../util/getUserName';

const { TableStore } = WeaTableNew;
const getLabel = WeaLocaleProvider.getLabel;

/**
 * 待办公文页面 数据对象
 */
export default class AccountListStore {
  @observable searchStore = new SearchStore();
  @observable columns = [
    { title: ' ', dataIndex: 'name', key: 'name' },
  ];
  @observable datas = [];
  @observable subWFDatas = {}
  @observable requestSubWFed = false;// 是否请求过子流程数据
  @observable current = 1;
  @observable count = 0;
  @observable pageSize = 10;
  @observable loading = false;
  @observable orderkey = '';
  @observable sortOrder = ''
  @observable inPortal = false;

  @action.bound
  setMobxState(params) {
    Object.keys(params).map((key) => {
      this[key] = params[key];
    });
  }

  @action
  setShowSearchAd = (showSearchAd) => {
    this.showSearchAd = showSearchAd;
  }

  setCount = (count) => {
    this.count = count;
  }

  setOrderkey = (orderkey) => {
    this.orderkey = orderkey;
  }

  setSortOrder = (sortOrder) => {
    this.sortOrder = sortOrder;
  }


  constructor() {
    this.searchStore.setSearchType(2);
  }

  // 构建搜索条件
  buildSearchCondition(module, params = {}) {
    API_SEARCH_REQ.getCondition(params).then((data) => {
      this.searchStore.setSearchCondition(data);
      const conditioninfo = data.condition;
      this.searchStore.form.initFormFields(conditioninfo);
    });
  }

  @action
  changeShowSize=(current, pageSize, params)=> {
    this.current = current;
    this.pageSize = pageSize;
    this.doSearch(params);
  }

  // 执行搜索，刷新表格对象数据
  @action.bound
  doSearch(params = {}, resetCurrent = false) {
    if (resetCurrent) {
      this.current = 1;
    }
    let param = params;
    this.loading = true;
    API_SEARCH_REQ.getSearchReqList(param).then((data) => {
      this.doSearch2(data);
      this.loading = false;
    });

    return this;
  }

  @action.bound
  doSearch2(params) {
    this.requestSubWFed = false;
    let p = {
      dataKey: params.generateParams.sessionkey,
      current: this.current,
      pageSize: this.pageSize,
    };
    API_SEARCH_REQ.pageSize({ dataKey: params.generateParams.sessionkey, pageSize: this.pageSize }).then(() => {
      API_SEARCH_REQ.getTableDatas(p).then((data) => {
        const renderContent = value => (<a dangerouslySetInnerHTML={{ __html: value }} />);
        const renderOdocInfo = (value, row) => {
          if (row.parameter_id != '') {
            return (<a style={{ color: '#4d7ad8' }} onClick={() => this.changeDailogStatus(value)}>{getLabel(388097, '收文单位信息')}</a>);
          }
        };
        let columns_display = [];
        data.columns.forEach((element) => {
          if (element.display && element.display == 'true') {
            if (Object.prototype.hasOwnProperty.call(element, 'transMethodOther') === true) {
              element.render = renderContent;
            }
            if (element.dataIndex == 'parameter_id') {
              element.render = renderOdocInfo;
            }

            if (element.orderkey == 'zbr') {
              element.render = (text, record) => (
                <div id={`${record.requestid}todo`}>
                  <span style={{ cursor: 'pointer', textDecoration: 'underline' }} onClick={() => getTodo(record.requestid, `${record.requestid}todo`)}>{getLabel('26523', '显示')}</span>
                </div>
              );
            }
            if (element.orderkey == 'wbr') {
              element.render = (text, record) => (
                <div id={`${record.requestid}doing`}>
                  <span style={{ cursor: 'pointer', textDecoration: 'underline' }} onClick={() => getDoing(record.requestid, `${record.requestid}doing`)}>{getLabel('26523', '显示')}</span>
                </div>
              );
            }
            if (element.dataIndex == 'urgencydegree') {
              element.render = (text, record) => (
                <div id={`${record.requestid}doing`}>
                  <span dangerouslySetInnerHTML={{ __html: text }} />
                </div>
              );
            }
            element.sorter = true;
            columns_display.push(element);
          }
        });

        let datas_display = [];
        let hasSubWFRequestIdArr = [];
        // 只拿只想要的datas 其余的数据不要
        data.datas.forEach((d, i) => {
          let tepmData = {};
          columns_display.forEach((element) => {
            let key = `${element.dataIndex}span`;
            tepmData[element.dataIndex] = d[key];
          });
          tepmData.key = i;
          tepmData.subrequestInfospan = d.subrequestInfospan;
          tepmData.requestid = d.requestid;
          datas_display.push(tepmData);
          // 用来请求子流程用的
          if (d.subrequestInfospan == '1') {
            hasSubWFRequestIdArr.push(d.requestid);
          }
        });
        if (hasSubWFRequestIdArr.length > 0) {
          this.getAllSubWF(hasSubWFRequestIdArr);
        } else {
          this.subWFDatas = {};
          this.requestSubWFed = false;
        }

        this.columns = columns_display;
        this.datas = datas_display;
      });
    });

    if (this.orderkey !== '' && this.sortOrder !== '') {
      let sortParam = [{ orderkey: `${this.orderkey}`, sortOrder: `${this.sortOrder}` }];
      p.sortParams = JSON.stringify(sortParam);
    }

    API_SEARCH_REQ.getTableCounts(p).then((data) => {
      this.setCount(data.count);
    });
  }

  // 高级搜索面板隐藏和显示切换
  changeShowSearchAd(b) {
    this.setShowSearchAd(b);
  }

  resetForm() {
    this.searchStore.resetSearchForm();
    this.setSearchsBaseValue('');
  }

  getSearchsBaseValue() {
    return this.searchStore.form.getFormParams().requestname;
  }

  setSearchsBaseValue(v) {
    this.searchStore.form.updateFields({
      requestname: {
        value: v,
      },
    });
    this.searchStore.isSearched();
  }

  /* ----------------------收文详情弹窗------------------------------*/
  @observable visiable = false;
  @observable tableStore = new TableStore();
  @observable selectedRowKeys = [];
  @observable identifier = '';
  @observable reasonDialogShow = false;
  @observable backoutForm = new WeaForm();
  @observable companyId = '';
  @observable resendDocId = '';


  @action.bound
  changeDailogStatus(identifier = '') {
    this.identifier = identifier.split('&&')[0] || '';
    this.companyId = identifier.split('&&')[1] || '';
    this.resendDocId = identifier.split('&&')[2] || '';
    this.visiable = !this.visiable;
    this.visiable && this.getDialogTable();
    this.selectedRowKeys = [];
  }

  @action.bound
  getDialogTable(value = '') {
    const params = {
      entityName: value,
      documentId: this.identifier,
    };
    API_SEARCH_REQ.getDialogTable(params).then((data) => {
      if (data.sessionkey) {
        this.tableStore.getDatas(data.sessionkey);
      }
    });
  }

  @action.bound
  rowSelection(selectedRowKeys, selectedRows) {
    for (let i of selectedRows) {
      this.selectedRowKeys.push(i.receive_company_id);
    }
  }

  // 撤销提交
  @action.bound
  repeal() {
    const formData = this.backoutForm.getFormParams();
    const params = {
      ids: this.companyId,
      receiverDepartments: this.selectedRowKeys.join(','),
      status: '4',
      detail: formData.detail, // 处理意见
    };
    API_SEARCH_REQ.revokedDoc(params).then((data) => {
      if (data.api_status) {
        this.ReasonDialogStatus();
        this.changeDailogStatus();
        this.doSearch();
        message.success(getLabel('30700', '操作成功'));
      } else {
        message.error(data.api_errormsg);
      }
    });
  }

  @action.bound
  postOther(ids) {
    const params = {
      receiverDepartments: ids,
      ids: this.resendDocId,
      status: '0',
    };
    API_SEARCH_REQ.resendDoc(params).then((data) => {
      if (data.api_status) {
        this.changeDailogStatus();
        message.success(getLabel('27564', '发送成功'));
      } else {
        message.error(data.api_errormsg);
      }
    });
  }

  @action.bound
  onOperatesClick(record) {
    this.selectedRowKeys = [];
    this.selectedRowKeys.push(record.receive_company_id);
    this.ReasonDialogStatus();
  }

  @action.bound
  ReasonDialogStatus() {
    this.reasonDialogShow = !this.reasonDialogShow;
    this.backoutForm.resetForm();
  }

  // 获取撤销的form
  @action.bound postWebSendDocCondition() {
    API_SEARCH_REQ.postWebSendDocCondition().then((data) => {
      this.backoutForm.setCondition(data.undoCondition);
    });
  }

  @action.bound
  getAllSubWF(requestidArr) {
    const params = {
      requestids: requestidArr.join(','),
    };
    API_SEARCH_REQ.getSubReqInfo(params).then((datas) => {
      this.requestSubWFed = true;
      this.subWFDatas = datas;
    });
  }
}
